﻿//-----------------------------------------------------------------------
// <copyright file="RelayCommand.cs" company="WpfDevelopment.com">
//     Copyright WpfDevelopment.com. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace WpfDevelopment.MVVM
{
    using System;
    using System.Diagnostics;
    using System.Windows.Input;

    /// <summary>
    /// A way to relay a command to an action
    /// </summary>
    public class RelayCommand : ICommand
    {
        /// <summary>
        /// Occurs when changes occur that affect whether or not the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Gets or sets the execute command.
        /// </summary>
        /// <value>The execute command.</value>
        public Action<object> ExecuteCommand { get; set; }

        /// <summary>
        /// Gets or sets the can execute command.
        /// </summary>
        /// <value>The can execute command.</value>
        public Predicate<object> CanExecuteCommand { get; set; }

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require 
        /// data to be passed, this object can be set to null.</param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            return this.CanExecuteCommand(parameter);
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command 
        /// does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter)
        {
            if (this.CanExecuteCommand(parameter))
            {
                this.ExecuteCommand(parameter);
            }
            else
            {
                Debug.WriteLine("The relay command is not enabled, skipping execution of action");
            }
        }
    }
}
